

#include "byte_bit.h"

//if input_bit was not 0 or 1,the bit_to_byte will reset to rec frist bit
//when bit_to_byte was rec 8 bits, the return val is 1, otherwise return 0;
//LSB: Least Significant Bit(right bit, 0 bit), MSB: Most Significant Bit(lift bit, 8 bit)
uint8_t bit_to_byte_msb_frist(uint8_t* output_byte, uint8_t* count, uint8_t input_bit)
{
	(*output_byte) <<= 1;
	(*count)++;

	if(input_bit == 0){
	}
	else if(input_bit == 1){
		(*output_byte) |= 1;
	}
	else{
		(*output_byte) = 0;
		(*count) = 0;
	}

	if((*count) >= 8){
		(*count) = 0;
		return 1;
	}
	else{
		return 0;
	}
}
uint8_t bit_to_byte_lsb_frist(uint8_t* output_byte, uint8_t* count, uint8_t input_bit)
{
	(*output_byte) >>= 1;
	(*count)++;

	if(input_bit == 0){
	}
	else if(input_bit == 1){
		(*output_byte) |= 0x80;
	}
	else{
		(*output_byte) = 0;
		(*count) = 0;
	}

	if((*count) >= 8){
		(*count) = 0;
		return 1;
	}
	else{
		return 0;
	}
}

uint8_t byte_to_bit_msb_frist(uint8_t* output_bit, uint8_t* count, uint8_t input_byte)
{
	uint8_t mark = 0x80>>(*count);

	if(input_byte&mark){
		(*output_bit) = 1;
	}
	else{
		(*output_bit) = 0;
	}
	(*count)++;

	if((*count) > 8){
		(*count) = 0;
		return 0;
	}
	else{
		return 1;
	}
}
uint8_t byte_to_bit_lsb_frist(uint8_t* output_bit, uint8_t* count, uint8_t input_byte)
{
	uint8_t mark = 1<<(*count);

	if(input_byte&mark){
		(*output_bit) = 1;
	}
	else{
		(*output_bit) = 0;
	}
	(*count)++;

	if((*count) > 8){
		(*count) = 0;
		return 0;
	}
	else{
		return 1;
	}
}
/*
void main()
{
	uint8_t bit_1;
	uint8_t byte_1;
	uint8_t count_1;

	uint8_t bit;
	uint8_t byte;
	uint8_t count;

	byte = 0xaa;
	count = 0;
	count_1 = 0;
	while(byte_to_bit_msb_frist(&bit, &count, byte) == 1){
		printf("%d ", bit);
		if(bit_to_byte_msb_frist(&byte_1, &count_1, bit) == 1){
			printf(" ----> %x \r\n", byte_1);
		}
	}

	byte = 0xf0;
	count = 0;
	count_1 = 0;
	while(byte_to_bit_lsb_frist(&bit, &count, byte) == 1){
		printf("%d ", bit);
		if(bit_to_byte_lsb_frist(&byte_1, &count_1, bit) == 1){
			printf(" ----> %x \r\n", byte_1);
		}
	}
}
*/